library(cregg)
library(estimatr)
library(sjPlot)
library(dplyr)
library(ggplot2)
library(tikzDevice)
library(grDevices)


make_ldp_differences_plot <- function(formatted_data){
  # Function to reproduce the LDP preference plot. Reproduces the mm_diff 
  # function from cregg, which is broken. 
  

  ldp_diff <- cregg::cj(formatted_data, 
            estimate = "mm", 
            formula = cand_vote ~ local_status + party,
            id = "ResponseId",
            by = ~ldp_supporter)
  
  ldp_diff <- ldp_diff %>% 
    group_split(ldp_supporter)
  
  non_ldp_supporter <- table(formatted_data$ldp_supporter)[1]
  ldp_supporter <- table(formatted_data$ldp_supporter)[2]
  
  mm_diffs <- ldp_diff[[2]]$estimate - ldp_diff[[1]]$estimate
  pooled_se <- sqrt(ldp_diff[[1]]$std.error^2 + ldp_diff[[2]]$std.error^2)
  
  lower <- mm_diffs - pooled_se*1.959964 
  upper <- mm_diffs + pooled_se*1.959964 
  
  diff_plot_data <- cbind(mm_diffs, lower, upper)
  
  level_name <- ldp_diff[[1]]$level
  
  diff_plot_data <- as.data.frame(diff_plot_data)
  diff_plot_data <- cbind(level_name, diff_plot_data)
  
  ldp_diff_plot <- diff_plot_data[1:3, ] %>%
    ggplot(aes(y = level_name, x = mm_diffs, xmin = lower, xmax = upper)) +
    geom_point() +
    geom_errorbar(width = 0) + 
    geom_vline(xintercept = 0, linetype = "dashed") + 
    scale_y_discrete(name = "level") + 
    scale_x_continuous(name = "Difference in Marginal Means (LDP Identifiers vs Others)") + 
    theme_bw()
  
  return(ldp_diff_plot)
}

path_to_data <- "data"
formatted_survey_file <- "follow_up_survey_formatted.rds"

path_to_figures <- "figures"
path_to_paper_figures <- "paper_plots"
path_to_appendix_figures <- "appendix_plots"

aichaku_plot <- "aichaku_interactions.eps"
elite_plot <- "elite_status_interactions.eps"
ldp_plot <- "ldp_mm_diff_plot.eps"


formatted_data <- readRDS(file.path(path_to_data, formatted_survey_file))
formatted_data$Q213_1 <- as.numeric(formatted_data$Q213_1)
formatted_data$Q219_1 <- as.numeric(formatted_data$Q219_1)

# Estimates AMCEs using lm_robust
aichaku_local_status_interaction <- lm_robust(data = formatted_data, formula = cand_vote ~ party + Q213_1*local_status, clusters = respondent)
elite_perception_local_status_interaction <- lm_robust(data = formatted_data, formula = cand_vote ~ party + Q219_1*local_status, clusters = respondent)


# plot_model makes plots of linear interaction models
aichaku_interaction_plot <- plot_model(aichaku_local_status_interaction,
                                       type = "int",
                                       terms = c("local_status", "Q213_1"),
                                       title = "") +
  scale_color_discrete(name = "Candidate Type") + 
  scale_fill_discrete(name = "Candidate Type") +
  scale_x_continuous(name = "Level of Attachment to Local Community (1 = low, 4 = high)") + 
  scale_y_continuous(name = "Predicted Outcome Mean") +
  theme_bw()


elite_status_interaction_plot <- plot_model(elite_perception_local_status_interaction, 
           type = "int",
           terms = c("local_status", "Q219_1"),
           title = "") + 
  scale_color_discrete(name = "Candidate Type") + 
  scale_fill_discrete(name = "Candidate Type") +
  scale_x_continuous(name = "Self-Perception of Elite Status (1 = low, 10 = high)") + 
  scale_y_continuous(name = "Predicted Outcome Mean") +
  theme_bw()

ldp_diff_plot <- make_ldp_differences_plot(formatted_data)

vote_choice_formula <- 
  cand_vote ~ local_status + party

ggsave(
  filename = file.path(path_to_figures, path_to_appendix_figures, aichaku_plot),
  plot = aichaku_interaction_plot,
  height = 7, 
  width = 7,
  units = "in",
  device = cairo_ps,
  fallback_resolution = 200)

ggsave(
  filename = file.path(path_to_figures, path_to_appendix_figures, elite_plot),
  plot = elite_status_interaction_plot,
  height = 7, 
  width = 7,
  units = "in",
  device = cairo_ps,
  fallback_resolution = 200)

ggsave(
  filename = file.path(path_to_figures, path_to_appendix_figures, ldp_plot),
  plot = ldp_diff_plot,
  height = 7, 
  width = 7,
  units = "in",
  device = cairo_ps,
  fallback_resolution = 200)



